package com.efounder.ui;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;

import androidx.annotation.Nullable;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.builder.base.data.ESPRowSet;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.mobilecomps.R;
import com.efounder.view.PullListView;
import com.pizidea.imagepicker.ui.LoadingDataUtilBlack;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_ADDRESS;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PORT;


/**
 * 流程已办fragment
 * 孙立鹏 on 2017/3/29 10:04
 */

public class EndTaskFragment extends BaseFragment{

    private View mView;
    private PullListView lv;
    private MyAdapter adapter;
    private List<ESPRowSet> rowSetList1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.flowpath, null);

        lv = (PullListView) mView.findViewById(R.id.task_listview);

        firstLoadData();

        initView();


        return mView;
    }

    private void initView() {
        lv.setOnRefreshListener(new PullListView.OnRefreshListener() {

            @Override
            public void onRefresh() {
                loadDataFromNet(adapter);
            }
        });
        lv.setOnGetMoreListener(new PullListView.OnGetMoreListener() {

            @Override
            public void onGetMore() {
                loadMoreData(adapter);

            }
        });

//        lv.performRefresh();
    }


    //ViewHolder静态类
    static class ViewHolder
    {
        public TextView taskname;
        public TextView date;
        public TextView step;
        public TextView sponsor;
        public TextView submit;
        public TextView tasknum;
    }

    public class MyAdapter extends BaseAdapter {
        private LayoutInflater mInflater = null;
        private MyAdapter(Context context)
        {
            this.mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            //How many items are in the data set represented by this Adapter.
            //在此适配器中所代表的数据集中的条目数
            return rowSetList1.size();
        }

        @Override
        public Object getItem(int position) {
            // Get the data item associated with the specified position in the data set.
            //获取数据集中与指定索引对应的数据项
            return position;
        }

        @Override
        public long getItemId(int position) {
            //Get the row id associated with the specified position in the list.
            //获取在列表中与指定索引对应的行id
            return position;
        }

        //Get a View that displays the data at the specified position in the data set.
        //获取一个在数据集中指定索引的视图来显示数据
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            //如果缓存convertView为空，则需要创建View
            if(convertView == null)
            {
                holder = new ViewHolder();
                //根据自定义的Item布局加载布局
                convertView = mInflater.inflate(R.layout.task_item, null);
                holder.date = (TextView)convertView.findViewById(R.id.date);
                holder.step = (TextView)convertView.findViewById(R.id.step_tv);
                holder.sponsor = (TextView)convertView.findViewById(R.id.sponsor_tv);
                holder.submit  = (TextView)convertView.findViewById(R.id.submit_tv);
                holder.taskname = (TextView)convertView.findViewById(R.id.taskname_tv);
                //将设置好的布局保存到缓存中，并将其设置在Tag里，以便后面方便取出Tag
                convertView.setTag(holder);
            }else
            {
                holder = (ViewHolder)convertView.getTag();
            }
            EFRowSet rowSet = (EFRowSet) rowSetList1.get(position);
            Map<String, Object> dataMap = rowSet.getDataMap();

            long datenum = Long.valueOf(String.valueOf(dataMap.get("OP_TIME"))).longValue();
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date(datenum);
            String str = sdf.format(date);

            holder.taskname.setText(String.valueOf(dataMap.get("FLOW_NAME")));
            holder.date.setText(str);
            holder.step.setText(String.valueOf(dataMap.get("TASK_NAME")));
            holder.sponsor.setText(String.valueOf(dataMap.get("BIZ_SUBMIT_USER")));
            holder.submit.setText(String.valueOf(dataMap.get("OP_SUBMIT_USER")));
            holder.taskname.setText("RW"+ String.valueOf(dataMap.get("BIZ_DJBH")));

            return convertView;
        }

    }

    private void firstLoadData(){
        /*
      * 内部AsyncTask类
      */
        class GetTaskDataAsyncTask extends AsyncTask<String, Integer, EFDataSet> {
            long time = System.currentTimeMillis();
            // 进度显示
            protected void onPreExecute() {
                // 进度显示
                super.onPreExecute();
//                LoadingDataUtil.show();
                LoadingDataUtilBlack.show(getActivity());

            }

            @Override
            protected EFDataSet doInBackground(String... params) {

                EAI.Protocol = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE);

                EAI.Server = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS);
                EAI.Port = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT);
                EAI.Path = "OSPMobile";
                EAI.Service = "Android";
                JParamObject PO = JParamObject.Create();


                PO.setEnvValue("DBNO", EnvironmentVariable.getProperty("sign"));// 数据标示
                PO.setEnvValue("Product", EnvironmentVariable.getProperty(KEY_SETTING_APPID));// 服务名称

                // 防止盗用
                PO.setEnvValue(KEY_SETTING_APPID, "PGYDYYM");

                // 权限管理
                PO.SetValueByParamName("LOAD_GNQX", "1");
                JParamObject.assign(PO);
                JResponseObject RO = null;
                EFDataSet flowTaskDataSet = null;
                PO.SetValueByParamName("Method","processed");
                PO.SetValueByParamName("PageSize","5");
                PO.SetValueByParamName("PageNum","1");
                //PO.SetValueByParamName("F_ZGBH",EnvironmentVariable.getF_ZGBH());
                PO.SetValueByParamName("F_ZGBH","18972996678");
                try {
                    RO = EAI.DAL.SVR("TaskListQueryServerPlugin", PO);
                } catch (Exception e) {

                }
                if(RO!=null)
                    flowTaskDataSet = (EFDataSet) RO.getResponseObject();
                return  flowTaskDataSet;
            }

            // 当后台操作结束时，此方法将会被调用，计算结果将做为参数传递到此方法中，直接将结果显示到UI组件上
            protected void onPostExecute(EFDataSet result) {
//                LoadingDataUtil.dismiss();
                LoadingDataUtilBlack.dismiss();
                if(result==null){
                    return;
                }
                System.out.println(".....");
                rowSetList1 = result.getRowSetList();
                if(rowSetList1==null)
                    return;
                adapter = new MyAdapter(getContext());
                if(null != rowSetList1 && 0 != rowSetList1.size()){
                    lv.setAdapter(adapter);

                }
            }
        }


        new GetTaskDataAsyncTask().execute();
    }

    private void loadDataFromNet(final MyAdapter adapter){
        /*
      * 内部AsyncTask类
      */
        class GetTaskDataAsyncTask extends AsyncTask<String, Integer, EFDataSet> {
            long time = System.currentTimeMillis();
            // 进度显示
            protected void onPreExecute() {
                // 进度显示
                super.onPreExecute();
//                LoadingDataUtil.show();
//                LoadingDataUtilBlack.show(getActivity());

            }

            @Override
            protected EFDataSet doInBackground(String... params) {

                EAI.Protocol = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE);

                EAI.Server = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS);
                EAI.Port = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT);
                EAI.Path = "OSPMobile";
                EAI.Service = "Android";
                JParamObject PO = JParamObject.Create();


                PO.setEnvValue("DBNO", EnvironmentVariable.getProperty("sign"));// 数据标示
                PO.setEnvValue("Product", EnvironmentVariable.getProperty(KEY_SETTING_APPID));// 服务名称

                // 防止盗用
                PO.setEnvValue(KEY_SETTING_APPID, "PGYDYYM");

                // 权限管理
                PO.SetValueByParamName("LOAD_GNQX", "1");
                JParamObject.assign(PO);
                JResponseObject RO = null;
                EFDataSet flowTaskDataSet = null;
                PO.SetValueByParamName("Method","processed");
                PO.SetValueByParamName("PageSize","5");
                PO.SetValueByParamName("PageNum","1");
                //PO.SetValueByParamName("F_ZGBH",EnvironmentVariable.getF_ZGBH());
                PO.SetValueByParamName("F_ZGBH","18972996678");
                try {
                    RO = EAI.DAL.SVR("TaskListQueryServerPlugin", PO);
                } catch (Exception e) {

                }
                if(RO!=null)
                    flowTaskDataSet = (EFDataSet) RO.getResponseObject();
                return  flowTaskDataSet;
            }

            // 当后台操作结束时，此方法将会被调用，计算结果将做为参数传递到此方法中，直接将结果显示到UI组件上
            protected void onPostExecute(EFDataSet result) {
//                LoadingDataUtil.dismiss();
                LoadingDataUtilBlack.dismiss();
                if(result==null){
                    return;
                }
                System.out.println(".....");
                rowSetList1 = result.getRowSetList();
                if(rowSetList1==null)
                    return;

                if(null != rowSetList1 && 0 != rowSetList1.size()){
                    adapter.notifyDataSetChanged();
                    lv.refreshComplete();
                }
            }
        }

        new GetTaskDataAsyncTask().execute();
    }


    private void loadMoreData(final MyAdapter adapter){
        /*
      * 内部AsyncTask类
      */
        class GetTaskDataAsyncTask extends AsyncTask<String, Integer, EFDataSet> {
            long time = System.currentTimeMillis();
            // 进度显示
            protected void onPreExecute() {
                // 进度显示
                super.onPreExecute();
//                LoadingDataUtil.show();
            }

            @Override
            protected EFDataSet doInBackground(String... params) {

                EAI.Protocol = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE);

                EAI.Server = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS);
                EAI.Port = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT);
                EAI.Path = "OSPMobile";
                EAI.Service = "Android";
                JParamObject PO = JParamObject.Create();


                PO.setEnvValue("DBNO", EnvironmentVariable.getProperty("sign"));// 数据标示
                PO.setEnvValue("Product", EnvironmentVariable.getProperty(KEY_SETTING_APPID));// 服务名称

                // 防止盗用
                PO.setEnvValue(KEY_SETTING_APPID, "PGYDYYM");

                // 权限管理
                PO.SetValueByParamName("LOAD_GNQX", "1");
                JParamObject.assign(PO);
                JResponseObject RO = null;
                EFDataSet flowTaskDataSet = null;
                PO.SetValueByParamName("Method","processed");
                PO.SetValueByParamName("PageSize","5");
                PO.SetValueByParamName("PageNum","1");
                //PO.SetValueByParamName("F_ZGBH",EnvironmentVariable.getF_ZGBH());
                PO.SetValueByParamName("F_ZGBH","18972996678");
                try {
                    RO = EAI.DAL.SVR("TaskListQueryServerPlugin", PO);
                } catch (Exception e) {

                }
                if(RO!=null)
                    flowTaskDataSet = (EFDataSet) RO.getResponseObject();
                return  flowTaskDataSet;
            }

            // 当后台操作结束时，此方法将会被调用，计算结果将做为参数传递到此方法中，直接将结果显示到UI组件上
            protected void onPostExecute(EFDataSet result) {
//                LoadingDataUtil.dismiss();


                if(result==null){
                    return;
                }
                System.out.println(".....");
                List<ESPRowSet> rowSetList2 = result.getRowSetList();
                if(rowSetList2==null)
                    return;
                rowSetList1.addAll(rowSetList2);
                // 通知listview加载完毕
                adapter.notifyDataSetChanged();
                lv.getMoreComplete();
            }
        }

        new GetTaskDataAsyncTask().execute();
    }
}
